<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wan-lei8.gitee.io","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="limit深分页为什么会变慢？">
<meta property="og:type" content="article">
<meta property="og:title" content="深分页问题">
<meta property="og:url" content="https://wan-lei8.gitee.io/2022/03/10/%E6%B7%B1%E5%88%86%E9%A1%B5%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="程序员西桐">
<meta property="og:description" content="limit深分页为什么会变慢？">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4Q8HORmtHgGO5ONMUOEcicLouyDJeeBfKHyvaS0Mz8dfOGw2tZKBibtOA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4nTPoSvhNeUybIzxEuhTsysxf5evGyibf7WCJEl5smI57HLajQ2hR22A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4ia1aE1rYAcI5Bvf9wuDZc5lqiau4nFfSRkAURMArRicibhkctmDEyTQTPg/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4TCjSaFqe1ibeovHNr3nA6dvVpT5EpwnEk5dYiaIibFDbneXV5pQF3WWVQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4MhictMicoM4ukM31bR0BLjACpxViasVjY8GOX65JxwrVuUvtRugfPSh9A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4fGGsPrxJkyfV1Hb9HHawzpFQGFoOwmgaAseTqibWKFPbXic1VkRgKxkA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4OqB9KbO6jeMkXPKmuaEfV9vXlKVPADrppwniaBku2yZ4P4kRUUcSQog/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4uChAfb7a2FDSkEowRmJFfM2lI8mKePwXLVicBK57mThibsT8bLS5LOQw/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4rEbOtrxXdRYCWh5WX2icSAicp7qnQTZ6qVBfuufdKvwymibdwibHSXN5icQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4Qhx5Bep7xFgGCWVNpIcYr8uLjocwRh3Trib65JWeBpaoEiaBWAvEUaDQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">
<meta property="article:published_time" content="2022-03-10T03:45:12.000Z">
<meta property="article:modified_time" content="2022-03-10T03:46:48.700Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4Q8HORmtHgGO5ONMUOEcicLouyDJeeBfKHyvaS0Mz8dfOGw2tZKBibtOA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1">

<link rel="canonical" href="https://wan-lei8.gitee.io/2022/03/10/%E6%B7%B1%E5%88%86%E9%A1%B5%E9%97%AE%E9%A2%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深分页问题 | 程序员西桐</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">程序员西桐</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">但行好事，莫问前程</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wan-lei8.gitee.io/2022/03/10/%E6%B7%B1%E5%88%86%E9%A1%B5%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员西桐">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深分页问题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-03-10 11:45:12 / 修改时间：11:46:48" itemprop="dateCreated datePublished" datetime="2022-03-10T11:45:12+08:00">2022-03-10</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="limit深分页为什么会变慢？"><a href="#limit深分页为什么会变慢？" class="headerlink" title="limit深分页为什么会变慢？"></a>limit深分页为什么会变慢？</h2><span id="more"></span>

<p>先看下表结构哈：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> account (</span><br><span class="line">  id <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT <span class="keyword">COMMENT</span> <span class="string">&#x27;主键Id&#x27;</span>,</span><br><span class="line">  <span class="type">name</span> <span class="type">varchar</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;账户名&#x27;</span>,</span><br><span class="line">  balance <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;余额&#x27;</span>,</span><br><span class="line">  create_time datetime <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;创建时间&#x27;</span>,</span><br><span class="line">  update_time datetime <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">ON</span> <span class="keyword">UPDATE</span> <span class="built_in">CURRENT_TIMESTAMP</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;更新时间&#x27;</span>,</span><br><span class="line">  <span class="keyword">PRIMARY KEY</span> (id),</span><br><span class="line">  KEY idx_name (<span class="type">name</span>),</span><br><span class="line">  KEY idx_update_time (update_time) //索引</span><br><span class="line">) ENGINE=InnoDB AUTO_INCREMENT=<span class="number">1570068</span> <span class="keyword">DEFAULT</span> CHARSET=utf8 ROW_FORMAT=REDUNDANT <span class="keyword">COMMENT</span>=<span class="string">&#x27;账户表&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p>假设深分页的执行SQL如下：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> id,<span class="type">name</span>,balance <span class="keyword">from</span> account <span class="keyword">where</span> update_time&gt; <span class="string">&#x27;2020-09-19&#x27;</span> <span class="keyword">limit</span> <span class="number">100000</span>,<span class="number">10</span>;</span><br></pre></td></tr></table></figure>

<p>这个SQL的执行时间如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4Q8HORmtHgGO5ONMUOEcicLouyDJeeBfKHyvaS0Mz8dfOGw2tZKBibtOA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>执行完需要<strong>0.742</strong>秒，深分页为什么会<strong>变慢</strong>呢？如果换成 <code>limit 0,10</code>，只需要<strong>0.006</strong>秒哦</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4nTPoSvhNeUybIzxEuhTsysxf5evGyibf7WCJEl5smI57HLajQ2hR22A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>我们先来看下这个SQL的执行流程：</p>
<ol>
<li>通过<strong>普通二级索引树</strong>idx_update_time，过滤update_time条件，找到满足条件的记录ID。</li>
<li>通过ID，回到<strong>主键索引树</strong>，找到满足记录的行，然后取出展示的列（<strong>回表</strong>）</li>
<li>扫描满足条件的100010行，然后扔掉前100000行，返回。</li>
</ol>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4ia1aE1rYAcI5Bvf9wuDZc5lqiau4nFfSRkAURMArRicibhkctmDEyTQTPg/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片">SQL的执行流程</p>
<p><strong>执行计划</strong>如下：<img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4TCjSaFqe1ibeovHNr3nA6dvVpT5EpwnEk5dYiaIibFDbneXV5pQF3WWVQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p><strong>SQL变慢原因有两个</strong>：</p>
<ol>
<li>limit语句会先扫描offset+n行，然后再丢弃掉前offset行，返回后n行数据。也就是说<code>limit 100000,10</code>，就会扫描100010行，而<code>limit 0,10</code>，只扫描10行。</li>
<li><code>limit 100000,10</code> 扫描更多的行数，也意味着<strong>回表</strong>更多的次数。</li>
</ol>
<h2 id="通过子查询优化"><a href="#通过子查询优化" class="headerlink" title="通过子查询优化"></a>通过子查询优化</h2><p>因为以上的SQL，回表了100010次，实际上，我们只需要10条数据，也就是我们只需要10次回表其实就够了。因此，我们可以通过<strong>减少回表次数</strong>来优化。</p>
<h3 id="回顾B-树结构"><a href="#回顾B-树结构" class="headerlink" title="回顾B+ 树结构"></a>回顾B+ 树结构</h3><p>那么，如何减少回表次数呢？我们先来复习下B+树索引结构哈~</p>
<p>InnoDB中，索引分主键索引（聚簇索引）和二级索引</p>
<ul>
<li>主键索引，叶子节点存放的是整行数据</li>
<li>二级索引，叶子节点存放的是<strong>主键的值</strong>。</li>
</ul>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4MhictMicoM4ukM31bR0BLjACpxViasVjY8GOX65JxwrVuUvtRugfPSh9A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<h3 id="把条件转移到主键索引树"><a href="#把条件转移到主键索引树" class="headerlink" title="把条件转移到主键索引树"></a>把条件转移到主键索引树</h3><p>如果我们把查询条件，转移回到主键索引树，那就可以减少回表次数啦。转移到主键索引树查询的话，查询条件得改为<code>主键id</code>了，之前SQL的<code>update_time</code>这些条件咋办呢？抽到<strong>子查询</strong>那里嘛~</p>
<p>子查询那里怎么抽的呢？因为二级索引叶子节点是有主键ID的，所以我们直接根据<code>update_time</code>来查主键ID即可，同时我们把 <code>limit 100000</code>的条件，也转移到子查询，完整SQL如下：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> id,<span class="type">name</span>,balance <span class="keyword">FROM</span> account <span class="keyword">where</span> id &gt;= (<span class="keyword">select</span> a.id <span class="keyword">from</span> account a <span class="keyword">where</span> a.update_time &gt;= <span class="string">&#x27;2020-09-19&#x27;</span> <span class="keyword">limit</span> <span class="number">100000</span>, <span class="number">1</span>) <span class="keyword">LIMIT</span> <span class="number">10</span>;写漏了，可以补下时间条件在外面</span><br></pre></td></tr></table></figure>

<p>查询效果一样的，执行时间只需要0.038秒！</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4fGGsPrxJkyfV1Hb9HHawzpFQGFoOwmgaAseTqibWKFPbXic1VkRgKxkA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>我们来看下执行计划<img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4OqB9KbO6jeMkXPKmuaEfV9vXlKVPADrppwniaBku2yZ4P4kRUUcSQog/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>由执行计划得知，子查询 table a查询是用到了<code>idx_update_time</code>索引。首先在索引上拿到了聚集索引的主键ID,省去了回表操作，然后第二查询直接根据第一个查询的 ID往后再去查10个就可以了!</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4uChAfb7a2FDSkEowRmJFfM2lI8mKePwXLVicBK57mThibsT8bLS5LOQw/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>因此，这个方案是可以的~</p>
<h2 id="INNER-JOIN-延迟关联"><a href="#INNER-JOIN-延迟关联" class="headerlink" title="INNER JOIN 延迟关联"></a>INNER JOIN 延迟关联</h2><p>延迟关联的优化思路，<strong>跟子查询的优化思路其实是一样的</strong>：都是把条件转移到主键索引树，然后减少回表。不同点是，延迟关联使用了inner join代替子查询。</p>
<p>优化后的SQL如下：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span>  acct1.id,acct1.name,acct1.balance <span class="keyword">FROM</span> account acct1 <span class="keyword">INNER</span> <span class="keyword">JOIN</span> (<span class="keyword">SELECT</span> a.id <span class="keyword">FROM</span> account a <span class="keyword">WHERE</span> a.update_time &gt;= <span class="string">&#x27;2020-09-19&#x27;</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> a.update_time <span class="keyword">LIMIT</span> <span class="number">100000</span>, <span class="number">10</span>) <span class="keyword">AS</span>  acct2 <span class="keyword">on</span> acct1.id= acct2.id;</span><br></pre></td></tr></table></figure>

<p>查询效果也是杠杆的，只需要0.034秒</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4rEbOtrxXdRYCWh5WX2icSAicp7qnQTZ6qVBfuufdKvwymibdwibHSXN5icQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>执行计划如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/PoF8jo1PmpzQjK8LtLTKwUB65wxrxZb4Qhx5Bep7xFgGCWVNpIcYr8uLjocwRh3Trib65JWeBpaoEiaBWAvEUaDQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1" alt="图片"></p>
<p>查询思路就是，先通过<code>idx_update_time</code>二级索引树查询到满足条件的主键ID，再与原表通过主键ID内连接，这样后面直接走了主键索引了，同时也减少了回表。</p>
<h2 id="标签记录法"><a href="#标签记录法" class="headerlink" title="标签记录法"></a>标签记录法</h2><p>limit 深分页问题的本质原因就是：<strong>偏移量（offset）越大，mysql就会扫描越多的行，然后再抛弃掉。这样就导致查询性能的下降</strong>。</p>
<p>其实我们可以采用<strong>标签记录</strong>法，就是标记一下上次查询到哪一条了，下次再来查的时候，从该条开始往下扫描。<strong>就好像看书一样，上次看到哪里了，你就折叠一下或者夹个书签，下次来看的时候，直接就翻到啦</strong>。</p>
<p>假设上一次记录到100000，则SQL可以修改为：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span>  id,<span class="type">name</span>,balance <span class="keyword">FROM</span> account <span class="keyword">where</span> id &gt; <span class="number">100000</span> <span class="keyword">order</span> <span class="keyword">by</span> id <span class="keyword">limit</span> <span class="number">10</span>;</span><br></pre></td></tr></table></figure>

<p>这样的话，后面无论翻多少页，性能都会不错的，因为命中了<code>id</code>索引。但是这种方式<strong>有局限性</strong>：需要一种类似连续自增的字段。</p>
<h2 id="使用between…and…"><a href="#使用between…and…" class="headerlink" title="使用between…and…"></a>使用between…and…</h2><p>很多时候，可以将<code>limit</code>查询转换为已知位置的查询，这样MySQL通过范围扫描<code>between...and</code>，就能获得到对应的结果。</p>
<p>如果知道边界值为100000，100010后，就可以这样优化：</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select  <span class="built_in">id</span>,<span class="built_in">name</span>,balance FROM account <span class="keyword">where</span> <span class="built_in">id</span> <span class="keyword">between</span> <span class="number">100000</span> <span class="keyword">and</span> <span class="number">100010</span> order <span class="keyword">by</span> <span class="built_in">id</span>;</span><br></pre></td></tr></table></figure>

<h2 id="手把手实战案例"><a href="#手把手实战案例" class="headerlink" title="手把手实战案例"></a>手把手实战案例</h2><p>我们一起来看一个实战案例哈。假设现在有表结构如下，并且有<strong>200万</strong>数据.</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> account (</span><br><span class="line"> id <span class="type">varchar</span>(<span class="number">32</span>) <span class="keyword">COLLATE</span> utf8_bin <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;主键&#x27;</span>,</span><br><span class="line"> account_no <span class="type">varchar</span>(<span class="number">64</span>) <span class="keyword">COLLATE</span> utf8_bin <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">&#x27;&#x27;</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;账号&#x27;</span></span><br><span class="line"> amount <span class="type">decimal</span>(<span class="number">20</span>,<span class="number">2</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;金额&#x27;</span></span><br><span class="line"> <span class="keyword">type</span> <span class="type">varchar</span>(<span class="number">10</span>) <span class="keyword">COLLATE</span> utf8_bin <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;类型A，B&#x27;</span></span><br><span class="line"> create_time datetime <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;创建时间&#x27;</span>,</span><br><span class="line"> update_time datetime <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span> <span class="keyword">COMMENT</span> <span class="string">&#x27;更新时间&#x27;</span>,</span><br><span class="line"> <span class="keyword">PRIMARY KEY</span> (id),</span><br><span class="line"> KEY `idx_account_no` (account_no),</span><br><span class="line"> KEY `idx_create_time` (create_time)</span><br><span class="line"> ) ENGINE=InnoDB <span class="keyword">DEFAULT</span> CHARSET=utf8 <span class="keyword">COLLATE</span>=utf8_bin <span class="keyword">COMMENT</span>=<span class="string">&#x27;账户表&#x27;</span> </span><br></pre></td></tr></table></figure>

<p>业务需求是这样：获取最2021年的A类型账户数据，上报到大数据平台。</p>
<h3 id="一般思路的实现方式"><a href="#一般思路的实现方式" class="headerlink" title="一般思路的实现方式"></a>一般思路的实现方式</h3><p>很多伙伴接到这么一个需求，会直接这么实现了：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询上报总数量</span></span><br><span class="line">Integer total = accountDAO.countAccount();</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询上报总数量对应的SQL</span></span><br><span class="line">&lt;<span class="keyword">select</span> id =<span class="string">&#x27;countAccount&#x27;</span> resultType=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span><br><span class="line">  seelct <span class="keyword">count</span>(<span class="number">1</span>) </span><br><span class="line">  <span class="keyword">from</span> account</span><br><span class="line">  <span class="keyword">where</span> create_time &gt;=<span class="string">&#x27;2021-01-01 00:00:00&#x27;</span></span><br><span class="line">  and  type =<span class="string">&#x27;A&#x27;</span></span><br><span class="line">&lt;/<span class="keyword">select</span>&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算页数</span></span><br><span class="line"><span class="built_in">int</span> pageNo = total % pageSize == <span class="number">0</span> ? total / pageSize : (total / pageSize + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//分页查询，上报</span></span><br><span class="line"><span class="keyword">for</span>(<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; pageNo; i++)&#123;</span><br><span class="line"> List&lt;AcctountPO&gt; list = accountDAO.listAccountByPage(startRow,pageSize);</span><br><span class="line"> startRow = (pageNo<span class="number">-1</span>)*pageSize;</span><br><span class="line"> <span class="comment">//上报大数据</span></span><br><span class="line"> postBigData(list);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//分页查询SQL（可能存在limit深分页问题，因为account表数据量几百万）</span></span><br><span class="line">&lt;<span class="keyword">select</span> id =<span class="string">&#x27;listAccountByPage&#x27;</span> &gt;</span><br><span class="line">  seelct * </span><br><span class="line">  <span class="keyword">from</span> account</span><br><span class="line">  <span class="keyword">where</span> create_time &gt;=<span class="string">&#x27;2021-01-01 00:00:00&#x27;</span></span><br><span class="line">  and  type =<span class="string">&#x27;A&#x27;</span></span><br><span class="line">  limit <span class="meta">#&#123;startRow&#125;,#&#123;pageSize&#125;</span></span><br><span class="line">&lt;/<span class="keyword">select</span>&gt;</span><br></pre></td></tr></table></figure>

<h3 id="实战优化方案"><a href="#实战优化方案" class="headerlink" title="实战优化方案"></a>实战优化方案</h3><p>以上的实现方案，会存在limit深分页问题，因为account表数据量几百万。那怎么优化呢？</p>
<p>其实可以使用<strong>标签记录</strong>法，有些伙伴可能会有疑惑，<strong>id主键不是连续</strong>的呀，真的可以使用标签记录？</p>
<p>当然可以，id不是连续，我们可以通过<code>order by</code>让它连续嘛。优化方案如下：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询最小ID</span></span><br><span class="line">String  lastId = accountDAO.queryMinId();</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询最小ID对应的SQL</span></span><br><span class="line">&lt;<span class="keyword">select</span> id=<span class="string">&quot;queryMinId&quot;</span> returnType=“java.lang.String”&gt;</span><br><span class="line"><span class="keyword">select</span> MIN(id) </span><br><span class="line"><span class="keyword">from</span> account</span><br><span class="line"><span class="keyword">where</span> create_time &gt;=<span class="string">&#x27;2021-01-01 00:00:00&#x27;</span></span><br><span class="line">and type =<span class="string">&#x27;A&#x27;</span></span><br><span class="line">&lt;/<span class="keyword">select</span>&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">//一页的条数</span></span><br><span class="line">Integer pageSize = <span class="number">100</span>;</span><br><span class="line"></span><br><span class="line">List&lt;AcctountPO&gt; list ;</span><br><span class="line"><span class="keyword">do</span>&#123;</span><br><span class="line">   list = listAccountByPage(lastId,pageSize);</span><br><span class="line">   <span class="comment">//标签记录法，记录上次查询过的Id</span></span><br><span class="line">   lastId = list.get(list,size()<span class="number">-1</span>).getId();</span><br><span class="line">    <span class="comment">//上报大数据</span></span><br><span class="line">    postBigData(list);</span><br><span class="line">&#125;<span class="keyword">while</span>(CollectionUtils.isNotEmpty(list));</span><br><span class="line"></span><br><span class="line">&lt;<span class="keyword">select</span> id =<span class="string">&quot;listAccountByPage&quot;</span>&gt;</span><br><span class="line">  <span class="keyword">select</span> * </span><br><span class="line">  <span class="keyword">from</span> account </span><br><span class="line">  <span class="keyword">where</span> create_time &gt;=<span class="string">&#x27;2021-01-01 00:00:00&#x27;</span></span><br><span class="line">  and id &gt; <span class="meta">#&#123;lastId&#125;</span></span><br><span class="line">  and type =<span class="string">&#x27;A&#x27;</span></span><br><span class="line">  <span class="keyword">order</span> <span class="keyword">by</span> id <span class="keyword">asc</span>  </span><br><span class="line">  limit <span class="meta">#&#123;pageSize&#125;</span></span><br><span class="line">&lt;/<span class="keyword">select</span>&gt;</span><br></pre></td></tr></table></figure>



<p>–end–</p>

    </div>
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wan-lei8.gitee.io/2022/03/10/%E6%B7%B1%E5%88%86%E9%A1%B5%E9%97%AE%E9%A2%98/" title="深分页问题">https://wan-lei8.gitee.io/2022/03/10/深分页问题/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/03/10/group-by-%E8%AF%A6%E8%A7%A3/" rel="prev" title="group by 详解">
      <i class="fa fa-chevron-left"></i> group by 详解
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/03/10/%E4%B9%A6%E5%86%99%E9%AB%98%E8%B4%A8%E9%87%8FSQL%E7%9A%8430%E6%9D%A1%E5%BB%BA%E8%AE%AE/" rel="next" title="书写高质量SQL的30条建议">
      书写高质量SQL的30条建议 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#limit%E6%B7%B1%E5%88%86%E9%A1%B5%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BC%9A%E5%8F%98%E6%85%A2%EF%BC%9F"><span class="nav-number">1.</span> <span class="nav-text">limit深分页为什么会变慢？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%9A%E8%BF%87%E5%AD%90%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96"><span class="nav-number">2.</span> <span class="nav-text">通过子查询优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9E%E9%A1%BEB-%E6%A0%91%E7%BB%93%E6%9E%84"><span class="nav-number">2.1.</span> <span class="nav-text">回顾B+ 树结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8A%8A%E6%9D%A1%E4%BB%B6%E8%BD%AC%E7%A7%BB%E5%88%B0%E4%B8%BB%E9%94%AE%E7%B4%A2%E5%BC%95%E6%A0%91"><span class="nav-number">2.2.</span> <span class="nav-text">把条件转移到主键索引树</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#INNER-JOIN-%E5%BB%B6%E8%BF%9F%E5%85%B3%E8%81%94"><span class="nav-number">3.</span> <span class="nav-text">INNER JOIN 延迟关联</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A0%87%E7%AD%BE%E8%AE%B0%E5%BD%95%E6%B3%95"><span class="nav-number">4.</span> <span class="nav-text">标签记录法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8between%E2%80%A6and%E2%80%A6"><span class="nav-number">5.</span> <span class="nav-text">使用between…and…</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%8B%E6%8A%8A%E6%89%8B%E5%AE%9E%E6%88%98%E6%A1%88%E4%BE%8B"><span class="nav-number">6.</span> <span class="nav-text">手把手实战案例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E8%88%AC%E6%80%9D%E8%B7%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="nav-number">6.1.</span> <span class="nav-text">一般思路的实现方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E6%88%98%E4%BC%98%E5%8C%96%E6%96%B9%E6%A1%88"><span class="nav-number">6.2.</span> <span class="nav-text">实战优化方案</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=""
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name"></p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/malegod958@163.com" title="E-Mail → malegod958@163.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">万磊</span>
</div>
  <div class="powered-by">

  </div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='' opacity='0.5' zIndex='-1' count='99' src="/lib/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  
	<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
	

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
